import { useEffect, useState } from "react";
import { useMainStore } from "@/store/mainStore";
import { useNavigate } from "react-router-dom";
import styles from "./styles.module.less";
import {
  Button,
  Form,
  FormProps,
  Input,
  Image,
  message,
  Checkbox,
  Tooltip,
  Popover,
} from "antd";
import leftImg from "@/assets/images/qrsj_2.jpg";
import rightImg from "@/assets/images/qrsj_3.jpg";
import {
  ServerRegister,
  ServerLogin,
  ServerFindPassword,
} from "@go/app/ServerApp";
import { http } from "@/constant/status";
import { useShallow } from "zustand/react/shallow";
import { Icon } from "@iconify-icon/react";

const LoginPage = () => {
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();
  const { sideTab, appInfo } = useMainStore(
    useShallow((state) => ({
      sideTab: state.sideTab,
      appInfo: state.appInfo,
    }))
  );
  const [isRegister, setIsRegister] = useState(false);
  const [loading, setLoading] = useState(false);
  const [forgetLoading, setForgetLoading] = useState(false);
  const [isForget, setIsForget] = useState(false);

  const navigate = useNavigate();
  const goBack = () => {
    navigate(sideTab);
  };

  // 切换注册登录
  const changeStatus = (state: boolean) => {
    form1.resetFields();
    setIsRegister(state);
    if (state) {
      setIsForget(false);
    }
  };

  // 切换登录/找回密码
  const changeRotate = (state: boolean) => {
    if (state) {
      setIsForget(true);
      form1.resetFields();
    } else {
      setIsForget(false);
      form2.resetFields();
    }
  };

  const onFormChange = (val: FormProps, val2: FormProps) => {
    console.log(val2);
    // val2等同于form.getFieldsValue()，全字段
    // console.log("form", form.getFieldsValue());
  };

  const onFinish: FormProps["onFinish"] = (values) => {
    console.log("success value:", values);
  };

  // 注册
  const handleRegister = async () => {
    const values = await form1.validateFields();
    setLoading(true);
    try {
      const res = await ServerRegister(
        values.username,
        values.email,
        values.password
      );
      if (res.code !== http.StatusOK) {
        message.error(res.msg);
        return;
      }
      message.success("注册成功");
      changeStatus(false);
      // 将注册成功的账号密码填入登录框
      form1.setFieldsValue({
        username: values.username,
        password: values.password,
      });
    } catch (err) {
      message.error(`注册失败: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  // 登录
  const handleLogin = async () => {
    const values = await form1.validateFields();
    setLoading(true);
    try {
      const res = await ServerLogin(values.username, values.password);
      if (res.code !== http.StatusOK) {
        message.error(res.msg);
        return;
      }
      message.success("登录成功");
      console.log(res);
      useMainStore.setState({ isLogin: true, token: res.token });
      if (values.remember) {
        localStorage.setItem("loginInfo", JSON.stringify(values));
      }
      navigate(sideTab);
    } catch (err) {
      message.error(`登录失败: ${err}`);
    } finally {
      setLoading(false);
    }
  };

  // 找回密码
  const handleForget = async () => {
    const values = await form2.validateFields();
    setForgetLoading(true);
    try {
      const res = await ServerFindPassword(
        values.username,
        values.email,
        values.password
      );
      if (res.code !== http.StatusOK) {
        message.error(res.msg);
        return;
      }
      message.success("找回成功");
      changeRotate(false);
    } catch (err) {
      message.error(`登录失败: ${err}`);
    } finally {
      setForgetLoading(false);
    }
  };

  useEffect(() => {
    if (!isRegister && !isForget) {
      const loginInfo = localStorage.getItem("loginInfo");
      if (loginInfo) {
        form1.setFieldsValue(JSON.parse(loginInfo));
      }
    }
  }, [isRegister, isForget]);

  useEffect(() => {
    // TODO 判断token是否存在，存在则校验token是否有效，有效则直接跳转到首页
  }, []);

  return (
    <div className={styles.loginContainer}>
      <div className={styles.goBack}>
        <Button
          color="primary"
          variant="text"
          icon={<Icon icon="icon-park:back" />}
          onClick={goBack}
        >
          暂不登录
        </Button>
      </div>
      <div className={styles.content}>
        <Form
          className={[styles.formBox, styles.formFront].join(" ")}
          form={form1}
          onValuesChange={onFormChange}
          onFinish={onFinish}
          style={{
            transform: `translateX(${isRegister ? 100 : 0}%) rotateY(${
              isForget ? -180 : 0
            }deg)`,
          }}
          autoComplete="off"
        >
          {isRegister ? (
            <div className={styles.registerBox}>
              <h1>register</h1>
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: "请输入账号" },
                  { min: 4, message: "账号长度至少4位" },
                  { max: 20, message: "账号长度最多20位" },
                  { pattern: /^\S*$/, message: "账号不能包含空格" },
                ]}
              >
                <Input placeholder="账号" variant="borderless" />
              </Form.Item>
              <Form.Item
                name="email"
                rules={[
                  { type: "email", message: "这不是一个有效的邮箱" },
                  { required: true, message: "请输入邮箱" },
                ]}
              >
                <Input placeholder="邮箱" variant="borderless" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: "请输入密码" },
                  { min: 6, message: "密码长度至少6位" },
                  { max: 20, message: "密码长度最多20位" },
                  { pattern: /^\S*$/, message: "密码不能包含空格" },
                ]}
              >
                <Input.Password placeholder="密码" variant="borderless" />
              </Form.Item>
              <Form.Item
                name="confirm"
                dependencies={["password"]}
                rules={[
                  { required: true, message: "请再次输入密码" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue("password") === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次输入的密码不一致"));
                    },
                  }),
                ]}
              >
                <Input.Password placeholder="确认密码" variant="borderless" />
              </Form.Item>
              <Popover
                placement="top"
                content={
                  appInfo.register_off ? "注册功能维护中,暂不可用" : undefined
                }
              >
                <Button
                  disabled={appInfo.register_off}
                  loading={loading}
                  onClick={() => {
                    handleRegister();
                  }}
                >
                  注册
                </Button>
              </Popover>
            </div>
          ) : (
            <div className={styles.loginBox}>
              <h1>login</h1>
              <Form.Item
                name="username"
                rules={[{ required: true, message: "请输入账号" }]}
              >
                <Input placeholder="账号" variant="borderless" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password placeholder="密码" variant="borderless" />
              </Form.Item>
              <div className={styles.rememberLine}>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>记住密码</Checkbox>
                </Form.Item>
                <Button
                  className={styles.forgetBtn}
                  type="link"
                  onClick={() => {
                    changeRotate(true);
                  }}
                >
                  忘记密码
                </Button>
              </div>
              <Popover
                placement="top"
                content={
                  appInfo.login_off ? "登录功能维护中,暂不可用" : undefined
                }
              >
                <Button
                  disabled={appInfo.login_off}
                  loading={loading}
                  onClick={() => {
                    handleLogin();
                  }}
                >
                  登录
                </Button>
              </Popover>
            </div>
          )}
        </Form>
        <Form
          className={[styles.formBox, styles.formEnd].join(" ")}
          form={form2}
          // onValuesChange={onFormChange}
          onFinish={onFinish}
          style={{
            transform: `rotateY(${isForget ? 0 : 180}deg)`,
          }}
          autoComplete="off"
        >
          <div className={styles.loginBox}>
            <Button
              className={styles.backLogin}
              color="primary"
              variant="link"
              onClick={() => {
                changeRotate(false);
              }}
            >
              返回登录
            </Button>
            <h1>forget password</h1>
            <Form.Item
              name="username"
              rules={[
                { required: true, message: "请输入账号" },
                { min: 4, message: "账号长度至少4位" },
                { max: 20, message: "账号长度最多20位" },
                { pattern: /^\S*$/, message: "账号不能包含空格" },
              ]}
            >
              <Input placeholder="账号" variant="borderless" />
            </Form.Item>
            <Form.Item
              name="email"
              rules={[
                { type: "email", message: "这不是一个有效的邮箱" },
                { required: true, message: "请输入邮箱" },
              ]}
            >
              <Input placeholder="邮箱" variant="borderless" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, message: "请输入新密码" },
                { min: 6, message: "密码长度至少6位" },
                { max: 20, message: "密码长度最多20位" },
                { pattern: /^\S*$/, message: "密码不能包含空格" },
              ]}
            >
              <Input.Password placeholder="新密码" variant="borderless" />
            </Form.Item>
            <Form.Item
              name="confirm"
              dependencies={["password"]}
              rules={[
                { required: true, message: "请再次输入新密码" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("password") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次输入的密码不一致"));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="确认新密码" variant="borderless" />
            </Form.Item>
            <Popover
              placement="top"
              content={
                appInfo.forget_pwd_off ? "找回功能维护中,暂不可用" : undefined
              }
            >
              <Button
                disabled={appInfo.forget_pwd_off}
                loading={forgetLoading}
                onClick={() => {
                  handleForget();
                }}
              >
                找回
              </Button>
            </Popover>
          </div>
        </Form>
        <div className={[styles.conBox, styles.conLeft].join(" ")}>
          <h2>
            欢迎使用<span>小助手</span>
          </h2>
          <Image preview={false} src={leftImg} />
          <p>已有账号</p>
          <Button
            onClick={() => {
              changeStatus(false);
            }}
          >
            去登录
          </Button>
        </div>
        <div className={[styles.conBox, styles.conRight].join(" ")}>
          <h2>
            欢迎使用<span>小助手</span>
          </h2>
          <Image preview={false} src={rightImg} />
          <p>没有账号?</p>
          <Button
            disabled={isForget}
            onClick={() => {
              changeStatus(true);
            }}
          >
            去注册
          </Button>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
